<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>摄影网站后台管理系统</title>
    <style type="text/css">
        .float {
            float: left;
            width: 200px;
            height: 200px;
            overflow: hidden;
            border: 1px solid #CCCCCC;
            border-radius: 10px;
            padding: 5px;
            margin: 5px;
        }

        img {
            position: relative;
        }

        .result {
            width: 200px;
            height: 200px;
            text-align: center;
            box-sizing: border-box;
        }


        #file_input {
            display: none;
        }


        .delete {
            width: 200px;
            height: 200px;
            position: absolute;
            text-align: center;
            line-height: 200px;
            z-index: 10;
            font-size: 30px;
            background-color: rgba(255, 255, 255, 0.8);
            color: #777;
            opacity: 0;
            transition-duration: 0.7s;
            -webkit-transition-duration: 0.7s;
        }


        .delete:hover {
            cursor: pointer;
            opacity: 1;
        }


    </style>

    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#button').click(function () {
                var name = $("#id_username").val();
                var psw = $("#id_password").val();
                //var token = $('[name="csrfmiddlewaretoken"]').attr("value");
                if (name && psw) {
                    $.post("/jwt-login/",
                        {
                            "username": name,
                            "password": psw,
                            //"csrfmiddlewaretoken": token,
                            //Connection: 'keep-alive',
                        },
                        function (result) {
                            if (result.code == "100") {
                                window.location.href = "/home/";   //页面成功跳转
                            } else {
                                $("#msg").text(result.msg)          //页面失败显示提示语
                            }

                        });
                } else {
                    $("#msg").text("账号或密码不对！")
                }

            });
        })
    </script>
    <script type="text/javascript">
        window.onload = function () {
            var input = document.getElementById("file_input");
            var result;
            var dataArr = []; // 储存所选图片的结果(文件名和base64数据)
            var fd;  //FormData方式发送请求
            var oSelect = document.getElementById("select");
            var oAdd = document.getElementById("add");
            var oSubmit = document.getElementById("submit_picture");
            var oInput = document.getElementById("file_input");

            if (typeof FileReader === 'undefined') {
                alert("抱歉，你的浏览器不支持 FileReader");
                input.setAttribute('disabled', 'disabled');
            } else {
                input.addEventListener('change', readFile, false);
            }　　　　　//handler


            function readFile() {
                fd = new FormData();
                var iLen = this.files.length;
                for (var i = 0; i < iLen; i++) {
                    if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp|.DNG/i)) {　　//判断上传文件格式
                        return alert("上传的图片格式不正确，请重新选择");
                    }
                    var reader = new FileReader();
                    fd.append(i, this.files[i]);
                    reader.readAsDataURL(this.files[i]);  //转成base64
                    reader.fileName = this.files[i].name;

                    reader.onload = function (e) {
                        var imgMsg = {
                            name: this.fileName,//获取文件名
                            base64: this.result   //reader.readAsDataURL方法执行完后，base64数据储存在reader.result里
                        }
                        dataArr.push(imgMsg);
                        result = '<div class="delete">delete</div><div class="result"><img class="subPic" src="' + this.result + '" alt="' + this.fileName + '"/></div>';
                        var div = document.createElement('div');
                        div.innerHTML = result;
                        div['className'] = 'float';
                        document.getElementsByTagName('body')[0].appendChild(div);  　　//插入dom树
                        var img = div.getElementsByTagName('img')[0];
                        img.onload = function () {
                            var nowHeight = ReSizePic(this); //设置图片大小
                            this.parentNode.style.display = 'block';
                            var oParent = this.parentNode;
                            if (nowHeight) {
                                oParent.style.paddingTop = (oParent.offsetHeight - nowHeight) / 2 + 'px';
                            }
                        }
                        div.onclick = function () {
                            $(this).remove();                  // 在页面中删除该图片元素
                        }
                    }
                }
            }


            function send() {
                var paths = document.getElementById("file_input").files;
                if (paths.length == 0) {
                    alert("请选择文件");
                    return;
                }
                var formData = new FormData();
                $('.subPic').each(function () {
                        for (var i = 0; i < paths.length; i++) {
                            if ($(this).attr('alt') == paths[i].name) {
                                formData.append('files', paths[i]);
                            }
                        }
                    }
                );
                formData.append('album_id', '狗卑鄙家聚会');
                formData.append('status', 1);
                $.ajax({
                    url: 'http://127.0.0.1:8000/api/pictures/upload/',
                    type: 'post',
                    data: formData,
                    async: true,
                    dataType: 'formData',
                    processData: false,   //用FormData传fd时需有这两项
                    contentType: false,
                    success: function (data) {
                        console.log('返回的数据：' + JSON.stringify(data))
                    }
                })
            }


            oSelect.onclick = function () {
                oInput.value = "";   // 先将oInput值清空，否则选择图片与上次相同时change事件不会触发
                //清空已选图片
                $('.float').remove();
                oInput.click();
            }


            oAdd.onclick = function () {
                oInput.value = "";   // 先将oInput值清空，否则选择图片与上次相同时change事件不会触发
                oInput.click();
            }


            oSubmit.onclick = function () {
                if (!dataArr.length) {
                    return alert('请先选择文件');
                }
                send();
            }
        }

        /*
         用ajax发送fd参数时要告诉jQuery不要去处理发送的数据，
         不要去设置Content-Type请求头才可以发送成功，否则会报“Illegal invocation”的错误，
         也就是非法调用，所以要加上“processData: false,contentType: false,”
         * */


        function ReSizePic(ThisPic) {
            var RePicWidth = 200; //这里修改为您想显示的宽度值

            var TrueWidth = ThisPic.width; //图片实际宽度
            var TrueHeight = ThisPic.height; //图片实际高度

            if (TrueWidth > TrueHeight) {
                //宽大于高
                var reWidth = RePicWidth;
                ThisPic.width = reWidth;
                //垂直居中
                var nowHeight = TrueHeight * (reWidth / TrueWidth);
                return nowHeight;  //将图片修改后的高度返回，供垂直居中用
            } else {
                //宽小于高
                var reHeight = RePicWidth;
                ThisPic.height = reHeight;
            }
        }
    </script>
</head>
<body>
<!--这是一段注释。extends继承basepage.html页面-->
{% extends "Photography/basepage.html" %}

{% block content %}

    <div style="margin: 5% 40%;">
        <h1>欢迎登录后台管理系统！</h1>

        <form action="/login/" method="post">{% csrf_token %}
            <p>
                <label for="id_username">用户名：</label>
                <input type="text" id="id_username" name="username" autofocus required placeholder="这里输入账号"/> *
            </p>
            <p>
                <label for="id_password">密  码：</label>
                <input type="text" id="id_password" name="password" required="required" placeholder="这里输入密码"> *
            </p>
            <p style="color:red" id="msg">
                {{ msg }}
            </p>


        </form>
        <input type="submit" id="button" value="登录">
        <p>
            尚未注册？<a href="{% url 'Photography:user' %}">点击注册！</a>
        </p>
        忘记密码？<a href="{% url 'Photography:reset' %}">点击修改！</a>
        <br>
        <div class="container">
            <label>请选择一个图像文件：</label>
            <button id="select">(重新)选择图片</button>
            <button id="add">(追加)图片</button>
            <input type="file" id="file_input" multiple/>
            <button id="submit_picture">提交</button>
        </div>

    </div>
{% endblock content %}
</body>
</html>